package com.hxb.api.web.filter;

import java.io.IOException;
import java.util.Enumeration;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;

public class CharacterEncodingFilter implements Filter {
	private String urlEncoding = "ISO-8859-1";
	private String encoding;

	public void init(FilterConfig config) throws ServletException {
		encoding = config.getInitParameter("encoding");
	}

	public void doFilter(ServletRequest arg0, ServletResponse arg1,
			FilterChain chain) throws IOException, ServletException {
			HttpServletRequest request = (HttpServletRequest) arg0;
			HttpServletResponse response  = (HttpServletResponse) arg1;
			boolean isPost = request.getMethod().equalsIgnoreCase("post");
			if (isPost) {
				request.setCharacterEncoding(encoding);
				response.setCharacterEncoding(encoding);
			}else {
				Enumeration<String> names = request.getParameterNames();
				String name = null;
				String value = null;
				String[]  values = null;
				while(names.hasMoreElements()){
					name = names.nextElement();
					values = request.getParameterValues(name);
					for (int i = 0; i < values.length; i++) {
						value = values[i];
						if (StringUtils.isNotBlank(value)) {
							values[i] = new String(value.getBytes(urlEncoding), encoding);
						}
					}
				}
			}
			chain.doFilter(request, response);
	}

	public void destroy() {
		
	}
	
	
}